import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtButton, AtInput} from "taro-ui";
import {View} from '@tarojs/components'
import {TARO_ENV, CUSTOMIZATION_ADD} from "../../constants/api";
import {h5Wx} from "../../utils/h5.service";
import {newHttp} from "../../utils/request";
import {throttle} from "../../utils/tools";
import './custommade.scss'

export default class Custommade extends Component {
  state: {
    userForm: {
      destination: string
      phone: string
      btnDisabled: boolean
    }
  } = {
    userForm: {
      btnDisabled: false,
      destination: '',
      phone: ''
    }
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      h5Wx.getConfig()
    } else {
      Taro.hideShareMenu()
    }
  }

  handleChange(name, value) {
    this.state.userForm[name] = value
  }

  async submit() {
    const {userForm} = this.state
    const r = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;　　//1开头0-9内十位数
    if (!r.test(userForm.phone)) {
      Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
      return
    }
    this.setState({ btnDisabled: true }, async () => {
      try {
        const ret = await newHttp.catchPost(CUSTOMIZATION_ADD, userForm)
        if (ret) {
          Taro.showToast({title: ret, icon: 'none'})
          const time = setTimeout(() => {
            clearTimeout(time)
            Taro.switchTab({url: '/pages/index/index'})
          }, 1500)
        } else {
          this.setState({ btnDisabled: false })
        }
      } catch (e) {
        this.setState({ btnDisabled: false })
      }
    })
  }

  render() {
    const {userForm, btnDisabled} = this.state
    return (
      <View className='made-root'>
        <View className='content-box'>
          <View className='title'>定制旅行</View>
          <View className='desc'>其实可以很简单</View>
          <View className='form-box'>
            <View className='form-item form-item-top'>
              <AtInput className='require' name='name' type='text'
                value={userForm.destination} placeholder='请填写您想去的目的地'
                onChange={this.handleChange.bind(this, 'destination')}
              />
            </View>
            <View className='form-item'>
              <AtInput className='require' name='name' type='number' value={userForm.phone} placeholder='请填写您的手机号码'
                onChange={this.handleChange.bind(this, 'phone')}
              />
            </View>
          </View>
          <AtButton disabled={btnDisabled} onClick={throttle(this.submit.bind(this), 2000)} className='btn'>请帮我定制行程</AtButton>
        </View>
      </View>
    )
  }
}
